<?php

namespace App\server;

use App\Conf;
use App\controller\RegisterController;
use App\Log;
use Swoole\Table;

class TcpServer
{

    private $server;


    public function __construct()
    {
        $table = $this->setTable();
        $this->server = new \Swoole\Server(Conf::get("server.host"), Conf::get("server.port"));
        $this->server->table = $table;
        $this->init();
    }


    private function start()
    {
        $this->server->on("Start", function (\Swoole\Server $server) {

        });

        $this->server->on('WorkerStart', function ($server, $worker_id) {

            if ($worker_id >= $server->setting['worker_num']) {
                swoole_set_process_name("task worker");
                Log::workLog("tas", $worker_id);
            } else {
                swoole_set_process_name("event worker");
                Log::workLog("worker", $worker_id);
            }
        });
    }


    private function setConf()
    {
        $this->server->set(Conf::get("tcp"));
    }


    private function setConnect()
    {
        $this->server->on('Connect', [Conf::get('server.event'), "connect"]);
    }


    private function setReceive()
    {
        $this->server->on('Receive', [Conf::get('server.event'), "receive"]);
    }


    private function setClose()
    {
        $this->server->on('Close', [Conf::get('server.event'), "close"]);
    }


    private function setShutdown()
    {
        $this->server->on('Shutdown', [Conf::get('server.event'), "shutdown"]);
    }


    private function setWorkerExit()
    {
        $this->server->on('WorkerExit', function (\Swoole\Server $server, int $worker_id) {
            \Swoole\Timer::clearAll();
        });
    }


    private function setTable()
    {
        $table = new Table(1024,0.4);
//        $table->column('fd', Table::TYPE_INT);
        $table->column('time', Table::TYPE_INT);
        $table->column('printer', Table::TYPE_STRING,150);
//        $table->column('type', Table::TYPE_INT);
        $table->create();
        return $table;
    }


    public function init()
    {
        $this->setConf();
        $this->start();
        $this->setConnect();
        $this->setReceive();
        $this->setClose();
        $this->setShutdown();
        $this->setWorkerExit();
    }

    public function run(array $argv)
    {
        Log::initShow();
        $this->server->start();
    }
}